package org.xiaohanghu.starter;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * @author xiaohanghu
 */
public class JavaResources {

	protected Set<URL> resources = new HashSet<URL>();

	public void addJarResource(Collection<URL> urls) {
		for (URL url : urls) {
			addJarResource(url);
		}
	}

	public void addJarResource(URL url) {
		if (PathUtils.isJarUrl(url)) {
			resources.add(url);
		} else {// 如果不是一个jar文件，则按lib目录处理
			try {
				File dir = new File(url.toURI());
				addJarResource(dir);
			} catch (URISyntaxException e) {
				throw new IllegalStateException(e);
			}
		}
	}

	public void addJarResource(File file) {
		if (file.isDirectory()) {
			File[] listFiles = file.listFiles();
			for (File f : listFiles) {
				addJarResource(f);
			}
		} else {
			String name = file.getName();
			if (PathUtils.isJarPath(name)) {// 如果是一个jar文件
				this.resources.add(toURL(file));
			}
		}
	}

	/**
	 * classes根目录
	 * */
	public void addClassesResource(File dir) {
		this.resources.add(toURL(dir));
	}

	public void addClassesResource(Collection<URL> urls) {
		for (URL url : urls) {
			addClassesResource(url);
		}
	}

	public void addClassesResource(URL url) {
		this.resources.add(url);
	}

	public Set<URL> getResources() {
		return resources;
	}

	protected static URL toURL(File file) {
		try {
			return file.getCanonicalFile().toURI().toURL();
		} catch (IOException e) {
			throw new IllegalStateException(e);
		}
	}

	public String toClassPath() {
		if (resources.isEmpty()) {
			return null;
		}
		StringBuilder result = new StringBuilder();
		Iterator<URL> iterator = resources.iterator();
		if (iterator.hasNext()) {
			URL resource = iterator.next();
			String path = resource.getPath();
			result.append(path);
		}
		while (iterator.hasNext()) {
			result.append(File.pathSeparatorChar);
			URL resource = iterator.next();
			String path = resource.getPath();
			result.append(path);
		}
		return result.toString();
	}

	public static JavaResources getCurrentJavaResources()
			throws MalformedURLException {
		JavaResources javaResources = new JavaResources();
		String classPath = System.getProperty("java.class.path");
		// System.out.println(classPath);
		String[] paths = classPath.split(";");
		for (String path : paths) {
			File file = new File(path);
			if (file.isDirectory()) {
				javaResources.addClassesResource(file);
			} else {
				javaResources.addJarResource(file);
			}
		}
		return javaResources;
	}
}
